package com.workcell.workdata.im.component.listener;

import com.workcell.workdata.im.component.event.GroupEvent;
import com.workcell.workdata.im.component.event.PushMessageEvent;
import com.workcell.workdata.im.component.event.RevokerMessageEvent;
import com.workcell.workdata.im.constant.MessageAction;
import com.workcell.workdata.im.entity.EventMessage;
import com.workcell.workdata.im.entity.Message;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Component
public class MessageRevoker {

    private static final Consumer<RevokerMessageEvent> EMPTY_HANDLER = message -> {};

    private final Map<String, Consumer<RevokerMessageEvent>> revokerMap = new HashMap<>();

    @Resource
    private ApplicationContext applicationContext;


    public MessageRevoker(){
        revokerMap.put(MessageAction.ACTION_0,new ChatMessageRevoker());
        revokerMap.put(MessageAction.ACTION_3,new GroupMessageRevoker());
    }

    @EventListener
    public void onMessageRevokeEvent(RevokerMessageEvent event){
        String action = event.getMessage().getAction();
        revokerMap.getOrDefault(action,EMPTY_HANDLER).accept(event);
    }

    private class ChatMessageRevoker implements Consumer<RevokerMessageEvent>{

        @Override
        public void accept(RevokerMessageEvent event) {
            Message message = new EventMessage();
            message.setAction(MessageAction.ACTION_101);
            message.setSender(event.getMessage().getSender());
            message.setReceiver(event.getMessage().getReceiver());
            message.setContent(event.getMessage().getId().toString());
            applicationContext.publishEvent(new PushMessageEvent(message));
        }
    }

    private class GroupMessageRevoker implements Consumer<RevokerMessageEvent>{

        @Override
        public void accept(RevokerMessageEvent event) {

            /*
            被撤回的消息是这个UID发的
             */
            long uid = Long.parseLong(event.getMessage().getExtra());

            Message message = new EventMessage();
            message.setSender(event.getMessage().getSender());
            message.setAction(MessageAction.ACTION_310);
            message.setContent(event.getMessage().getId().toString());

            /*
             * 有可能是管理员撤回了消息
             */
            message.setExtra(String.valueOf(event.getUid()));

            GroupEvent groupEvent = new GroupEvent(message,uid);
            groupEvent.setReplaceable(false);
            groupEvent.addIgnored(uid);

            applicationContext.publishEvent(groupEvent);
        }
    }
}
